import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_learn/data_model.dart';

// JSON解析 与 Dart Model 的使用
class JsonParsingPage extends StatefulWidget {
  const JsonParsingPage({super.key});

  @override
  State<JsonParsingPage> createState() => _JsonParsingPageState();
}

class _JsonParsingPageState extends State<JsonParsingPage> {
  var resultShow = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('JSON解析 与 Dart Model 的使用')),
      body: Column(children: [_json2MapBtn(), _json2ModelBtn(), Text("返回结果：$resultShow")]),
    );
  }

  _json2MapBtn() {
    return ElevatedButton(
      onPressed: _json2Map,
      child: const Text('JSON字符串转Map'),
    );
  }

  _json2ModelBtn () {
    return ElevatedButton(onPressed: _json2Model, child: Text('JSON字符串转Model'));
  }

  void _json2Map() {
    var jsonString = '{"name":"张三","age":18}';
    Map<String, dynamic> map = jsonDecode(jsonString);
    setState(() {
      resultShow = '姓名：${map['name']}，年龄：${map['age']}';
    });
  }

  // jsonModel
  void _json2Model () {
    var jsonString = '{ "code": 0, "data": { "code": 0, "method": "GET", "requestPrams": "aa" }, "msg": "SUCCESS." }';
    Map<String, dynamic> map = jsonDecode(jsonString); // json转成map
    DataModel model = DataModel.fromJson(map); // 将map转化成Data Model
    setState(() {
      resultShow = 'code: ${model.code};requestParams: ${model.data?.requestPrams}';
    });
  }
}
